package admin

import (
	"invitation/internal/application"
	"invitation/internal/http/middleware"
	"invitation/internal/model"
	"invitation/internal/pojo/dto"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
)

func UpdateTeacherEndpoint(application *application.Application) func(ctx *fiber.Ctx) error {
	return func(ctx *fiber.Ctx) error {
		teacherReq := ctx.Locals(middleware.LocalKeysTeacherCreateRequest).(*dto.FirstTimePayload)
		log.Debug().Msgf("%v", teacherReq)
		if teacherReq.TeacherID == "" {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "teacherID is required",
			})
		}
		if _, err := application.RepoManager().FirstTimeTeacherInfoRepo().FindOneByTeacherID(teacherReq.TeacherID); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		txCtx, err := application.RepoManager().BeginTx(ctx.Context())
		if err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		defer func() {
			if err != nil {
				application.RepoManager().RollbackTx(txCtx)
			} else {
				application.RepoManager().CommitTx(txCtx)
			}
		}()
		teacherInfo := &model.FirstTimeTeacherInfo{
			TeacherID: teacherReq.TeacherID,
		}
		if teacherReq.Name != "" {
			teacherInfo.Name = teacherReq.Name
		}
		if teacherReq.Desc != "" {
			teacherInfo.Desc = teacherReq.Desc
		}
		log.Debug().Msgf("updateTeacherEndpoint:before teacherInfo:%v", teacherInfo)
		if err := application.RepoManager().FirstTimeTeacherInfoRepo().Update(teacherInfo); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		log.Debug().Msgf("updateTeacherEndpoint:teacherInfo:%v", teacherInfo)
		if teacherReq.PostportUrl != "" {
			if err := application.RepoManager().FirstTimePostportRepo().Update(teacherInfo.ID, teacherReq.PostportUrl); err != nil {
				return ctx.Status(500).JSON(fiber.Map{
					"message": err.Error(),
				})
			}
		}
		return ctx.Status(200).JSON(fiber.Map{
			"message": "success",
		})
	}
}
